package com.bnz.servlet;


import com.alibaba.fastjson.JSON;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.R;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService;
    @Override
    public void init() throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        studentService = wac.getBean(StudentService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String cmd = req.getParameter("cmd");
        if (StringUtils.isNotBlank(cmd)) {
            if ("list".equals(cmd)) {
                list(req,resp);
            }
            if ("findByPage".equals(cmd)) {
                findByPage(req,resp);
            }
        }
    }

    // 1. 查询所有学生
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Student> studentList = studentService.findAll();
        R students = R.ok().data("students", studentList);
        resp.getWriter().println(JSON.toJSONString(students));
        resp.getWriter().flush();
    }

    // 2. 分页查询所有学生
    private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 2.1 拿到当前页每页大小
        int page = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        // 2.2 开始分页查询
        PageResult<Student> pr = studentService.findByPage(page, pageSize);
        resp.getWriter().println(JSON.toJSONString(R.ok().data("pr",pr)));
        resp.getWriter().flush();


    }
}
